package com.example.demo.controller;

import com.example.demo.pojo.Address;
import com.example.demo.service.AddressService;
import com.example.demo.utill.ResponseResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/address")
public class AddressController {
    @Resource
    private AddressService addressService;

    @RequestMapping("/byId")
    @ResponseBody
    public ResponseResult selectByUid(HttpSession session){
        int uid=(int)session.getAttribute("userId");
        List<Address> list=addressService.selectAddressById(uid);
        ResponseResult res=new ResponseResult();
        if(list.toString().equals("[]")){
            res.setCode(500);
            res.setMessage("该用户没有设置过地址");
        }else{
            res.setCode(200);
            res.setData(list);
        }
        return res;
    }

    @RequestMapping("/addAddress")
    @ResponseBody
    public ResponseResult addAddress(Address address, HttpSession session){
        int uid=(int)session.getAttribute("userId");
        address.setUserid(uid);
        int i=addressService.addAddress(address);
        ResponseResult res=new ResponseResult();
        if(i!=0){
            res.setCode(200);
        }else
        {
            res.setCode(500);
        }
        return res;
    }

    @RequestMapping("/updateAddress")
    @ResponseBody
    public ResponseResult updateAddress(Address address,HttpSession session){
        int uid=(int)session.getAttribute("userId");
        address.setUserid(uid);
        ResponseResult res=new ResponseResult();
        int i=addressService.updateAddress(address);
        if(i!=0){
            res.setCode(200);
        }else{
            res.setCode(500);
        }
        return res;
    }

    @RequestMapping("/delAddress")
    @ResponseBody
    public ResponseResult delAddress(int id){
        ResponseResult res=new ResponseResult();
        int i=addressService.delAddress(id);
        if(i!=0){
            res.setCode(200);
        }else
        {
            res.setCode(500);
        }
        return res;
    }
}
